<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Document</title>
    <link rel="stylesheet" th:href="@{/static/css/default.min.css}">
    <link rel="stylesheet" th:href="@{/static/css/atelier-lakeside-dark.min.css}">
    <script type="text/javascript" th:src="@{/static/js/markdown-it.min.js}"></script>
    <script type="text/javascript" th:src="@{/static/js/highlight.min.js}"></script>
    <script type="text/javascript" th:src="@{/static/js/highlightjs-line-numbers.min.js}"></script>
</head>
<body>
<textarea th:title="input" th:id="input"></textarea>
<div>
    <button th:onclick="handleSend()">发送</button>
</div>
<div th:id="result"></div>
<script>
    const md = window.markdownit({
        highlight: function (str, lang) {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return '<pre class="hljs"><code>' +
                        hljs.highlight(lang, str, true).value +
                        '</code></pre>';
                } catch (__) {
                }
            }
            return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
        }
    });
    const result = document.querySelector('#result');


    function handleSend() {
        let my_text = ""
        result.innerHTML = ""
        const content = document.getElementById("input").value;
        const endpoint = 'http://192.168.1.84:8080/ai/stream?message=' + content;
        console.log(endpoint);
        const eventSource = new EventSource(endpoint, {withCredentials: true});
        // 连接建立时触发
        eventSource.onopen = function (event) {
            console.log("建立链接", event)
        };
        // 接收到服务器端发送的数据时触发
        eventSource.onmessage = function (event) {
            let text_temp = JSON.parse(event.data).result.output.content;
            if (text_temp == null && JSON.parse(event.data).result.metadata.finishReason == 'STOP') {
                eventSource.close()
            } else {
                my_text = my_text + text_temp
                const render_text = md.render(my_text);
                result.innerHTML = render_text;
            }
        };
        // 连接出错时触发
        eventSource.onerror = function (event) {
            eventSource.close()
        };

    }
</script>
</body>
</html>